package com.atguigu.tingshu.search.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Assert;
import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch._types.SortOrder;
import co.elastic.clients.elasticsearch.core.SearchResponse;
import co.elastic.clients.elasticsearch.core.search.Hit;
import co.elastic.clients.elasticsearch.core.search.SearchProfile;
import com.atguigu.tingshu.album.AlbumFeignClient;
import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.model.album.BaseCategory1;
import com.atguigu.tingshu.model.search.AlbumInfoIndex;
import com.atguigu.tingshu.search.service.ItemService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.client.elc.ElasticsearchTemplate;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
@SuppressWarnings({"all"})
public class ItemServiceImpl implements ItemService {

    @Autowired
    private AlbumFeignClient albumFeignClient;

    @Autowired
    private ElasticsearchClient elasticsearchClient;

    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 更新所有分类下排行榜-手动调用
     */
    @Override
    public void updateLatelyAlbumRanking() {
        try {
            //获取所有的一级分类
            List<BaseCategory1> baseCategory1List = albumFeignClient.findAllCategory1().getData();
            Assert.notNull(baseCategory1List, "一级分类为空");
            for (BaseCategory1 baseCategory1 : baseCategory1List) {
                Long baseCategory1Id = baseCategory1.getId();
                String[] rankingDimensionArray = new String[]{"hotScore", "playStatNum", "subscribeStatNum", "buyStatNum", "commentStatNum"};
                for (String rankingDimension : rankingDimensionArray) {
                    //查询专辑信息
                    SearchResponse<AlbumInfoIndex> searchResponse = elasticsearchClient.search(s -> s
                                    .index("albuminfo")
                                    .query(q -> q
                                            .term(t -> t
                                                    .field("category1Id")
                                                    .value(baseCategory1Id)))
                                    .sort(so -> so
                                            .field(f -> f
                                                    .field(rankingDimension)
                                                    .order(SortOrder.Desc)))
                                    .size(10)
                            , AlbumInfoIndex.class);
                    //存入redis
                    List<Hit<AlbumInfoIndex>> hits = searchResponse.hits().hits();
                    if (CollectionUtil.isNotEmpty(hits)){
                        List<AlbumInfoIndex> albumInfoIndexList = hits.stream().map(hit -> hit.source()).collect(Collectors.toList());
                        String key = RedisConstant.RANKING_KEY_PREFIX + baseCategory1Id;
                        redisTemplate.opsForHash().put(key, rankingDimension, albumInfoIndexList);
                    }
                }
            }
        } catch (IOException e) {
            log.error("[搜索服务]更新排行榜异常：{}", e);
            throw new RuntimeException(e);
        }
    }
}
